package itdep.services.profile;

import ga.domain.repository.EntityRepository;
import ga.util.ImageUtils;
import itdep.domain.profile.Picture;
import itdep.domain.profile.Profile;
import itdep.services.IisEntityServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Ivan Khalopik
 * @version $Revision: 58 $ $Date: 2010-07-08 23:36:22 +0000 (Thu, 08 Jul 2010) $
 */
public class ProfileServiceImpl
		extends IisEntityServiceImpl<Profile, ProfileQuery>
		implements ProfileService {

	public ProfileServiceImpl(EntityRepository repository) {
		super(repository, Profile.class, ProfileQuery.class);
	}

	@Override
	@Transactional
	public void attachPhoto(Profile profile, InputStream inputStream) {
		try {
			final Picture picture = profile.getPhoto() != null ? profile.getPhoto() : new Picture();
			final BufferedImage image = ImageUtils.readImage(inputStream);
			final byte[] imageData = ImageUtils.encodeImage(image, ImageUtils.JPEG_FORMAT);
			picture.setData(imageData);
			profile.setPhoto(picture);
			save(profile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
